/* eslint-disable no-restricted-globals */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage, injectIntl } from 'react-intl';
import { stripesConnect } from '@folio/stripes/core';
import get from 'lodash/get';
import {
  Button,
  MultiColumnList,
  ButtonGroup
} from '@folio/stripes/components';
import { StripesConnectedSource } from '@folio/stripes/smart-components';
import SearchForm from '../../components/party-property/search-form';
import {  IfPermission } from '@folio/stripes/core';

class ClassifyGroup extends Component {
  static manifest = Object.freeze({

    selectParams: { initialValue: '' },
    resultCount: { initialValue: 5 },
    name:'classificationRecords',
    classificationRecords: {
      type: 'okapi',
      path: 'party/property',
      recordsRequired: '%{resultCount}',
      perRequest: 5,
      limitParam: 'limit',
      records: 'propertyGroup',
      GET: {
        params: {
          query: '( isDel = 0 %{selectParams} ) sortby metadata.updateDate '
        },
        staticFallback: { params: {} }
      }
    }
  });

  static propTypes = {
    stripes: PropTypes.shape({
      logger: PropTypes.object
    }).isRequired,
    resources: PropTypes.object,
    mutator: PropTypes.shape({
      selectParams: PropTypes.string,
      classificationRecords: PropTypes.object
    }).isRequired
  };

  constructor(props) {
    super(props);
    this.logger = props.stripes.logger;
    this.log = this.logger.log.bind(this.logger);
    this.state = {
      editOpen: false,
      editParams: {}
    };
  }

  componentDidMount() {
    this.source = new StripesConnectedSource(this.props, this.logger);
  }

  componentDidUpdate() {
    this.source.update(this.props, 'classificationRecords');
  }

  componentWillUnmount() {
    const { mutator  } = this.props;

    mutator.selectParams.replace('');
  }

  search = ({ requestPreferences, creds, ...formData }) => {
    const { mutator } = this.props;
    if (formData && formData.name) {
      const query = `and name =${formData.name}*`;

      mutator.selectParams.replace(query);
      if (this.source) {
        this.source.update(this.props, 'classificationRecords');
      }
    } else {
      mutator.selectParams.replace('');
      if (this.source) {
        this.source.update(this.props, 'classificationRecords');
      }
    }
  };

  delData = formData => {
    const { mutator,intl } = this.props;

    // eslint-disable-next-line no-alert
    if (confirm(intl.formatMessage({id:"ui-party.other.confirm.deletion"}))) {

      mutator.classificationRecords.DELETE({ id: formData.id }).then(() => {

      });
    }
  };

  moreData = () => {
    if (this.source) {
      this.source.fetchMore(30);
    }
  };

  openEditForm = params => {
    const { history } = this.props;
    if (!!params && !!params.id) {
      history.push('/activity/classify/edit/' + params.id);
    } else {
      history.push('/activity/classify/add');
    }
  };



  render() {
    const {  toModel,resources } = this.props;
    if (this.source) {
      this.source.update(this.props, 'classificationRecords');
    }

    const totalCount = this.source ? this.source.totalCount() : 0;
    const group = get(resources, 'classificationRecords.records', []);
    const formatter = {
      serialNumber: (
        <FormattedMessage id="ui-party.loans.columns.serialNumber" />
      ),
      parentName: (
        <FormattedMessage id="ui-party.loans.columns.property.parentName" />
      ),
      name: (
        <FormattedMessage id="ui-party.loans.columns.property.name" />
      ),
      sort: (
        <FormattedMessage id="ui-party.sort" />
      ),
      edit: <FormattedMessage id="ui-party.loans.columns.operating.edit" />
    };

    return (
      <div style={{ width:'610px', height:'700px' }}>
        <SearchForm
          onSubmit={this.search}
          toModel={toModel}
          openEdit={() => {
            this.openEditForm({ sort: 1 });
          }}
        />
        <MultiColumnList
          interactive={false}
          height={700}
          width={'630px'}
          isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
          totalCount={totalCount}
          contentData={group}
          virtualize
          onNeedMoreData={this.moreData}
          columnMapping={formatter}
          columnWidths={{
            serialNumber: '60px',
            parentName: '150px',
            name: '150px',
            sort: '60px',
            edit: '150px'
          }}
          visibleColumns={[
            'serialNumber',
            'name',
            'parentName',
            'sort',
            'edit'
          ]}
          formatter={{
            edit: item => [
              <ButtonGroup>
                <IfPermission perm={"ui-party.property.manage.view.edit"}>
                  <Button
                      onClick={() => {
                        toModel('/party/property/edit', { id:item.id });
                      }}
                  >
                    <FormattedMessage id={"ui-party.loans.columns.operating.edit"}/>
                  </Button>
                </IfPermission>
                <IfPermission perm={"ui-party.property.manage.view.delete"}>
                <Button
                  style={{ border: '1px solid #900', color: ' #900' }}
                  onClick={() => {
                    this.delData(item);
                  }}
                >
                  <FormattedMessage id={"ui-party.loans.columns.operating.remove"}/>
                </Button>
                </IfPermission>
              </ButtonGroup>
            ],
            serialNumber: item => [<span>{item.rowIndex + 1}</span>]
          }}
        />
      </div>
    );
  }

}

export default injectIntl(stripesConnect(ClassifyGroup));
